import axios from 'axios'
import store from 'store'

import base from '@/config/base.config'
const { TIME_OUT, TOKEN_NAME } = base
const serve = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: TIME_OUT,
})

// 2. 设置拦截器
/*
  请求处理拦截器只携带token, 所有请求带带上token
  响应拦截器, 将响应内容提取出来

*/

serve.interceptors.request.use(
  async (config) => {
    let token = store.get(TOKEN_NAME)

    if (token && token !== undefined) {
      config.headers['Authorization'] = `Bearer ${store.get(TOKEN_NAME)}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  },
)

// 拦截器, 如果响应为错误, 就走err
serve.interceptors.response.use(
  async (response) => {
    return response.data
  },
  (err) => {
    return Promise.reject(err)
  },
)

export default serve
